<?php

require_once( dirname( __FILE__ ) . '/../../categoryPage/actions/actions.class.php' ); // showin, showby actions

class homepageActions extends myFrontendAction{
	
	public $showByAr = array(6,9,12,15);
	public $showIn = array('list' => 'maincontent', # request value (stored in user session) => CSS class for products container
							'grid' => 'maincontent2');
	
	//public function preExecute(){}

	public function executeJoinMailGroup(sfWebRequest $request){
        $this->setLayout(false);
        sfProjectConfiguration::getActive()->loadHelpers(array('I18N'));

		$groups = $request->getParameter('grupp');
		if(@in_array(0, $groups)){
			$groups = array(2,3,4,5,6,7,8);
		}

		$email = urlencode($request->getParameter('email'));
		$groups = implode(':', $groups);


		$answer = file_get_contents('http://csi.poff.ee/csi_connect.php'.
				"?email={$email}&groups=" . $groups );

		if($answer == 'success' && $groups){
			$code = 200;
			$message = 'Olete uudiskirjaga liitunud';
		}else{
			$code = 500;
			$message = 'Kontrolli andmeid';
		}
		

        $this->renderPartial('global/json', array('item' => array('code' => $code,
                'message' => __($message)) ));

        return sfView::NONE;
	}

	
	public function executeIndex(sfWebRequest $request)
	{
		/*if($request->isXmlHttpRequest()) {
			$this->setLayout(false);
			
			return $this->renderComponent('projectsList', 'render');
		}*/
	}
	
	
	public function executeChangeCurrency(sfWebRequest $request){
		if(($cur = Doctrine::getTable('Currency')->find($this->getRequestParameter('currencyID')))){
			$this->getUser()->setCurrency($cur);
			
			$this->dispatcher->notify(new sfEvent($this, 'user.currency_changed'));	
		}
				
		$this->redirectToReferer();	
	}
	

	public function executePasswordReminder(sfWebRequest $request) {
		$form = new PasswordReminderForm();
		
		if($this->processReminderForm($form)){
			$this->getUser()->setFlash('reminder.message', 'check your email');
		}else{
			$this->getUser()->setFlash('reminder.message', 'wrong email');
		}
		
		$this->redirectToReferer();
	}
	
	
	public function executeShowby(sfWebRequest $request){
		if(in_array($this->getRequestParameter('val'), categoryPageActions::$showByAr)){
			$this->getUser()->setAttribute('showby', $this->getRequestParameter('val'));
		}
		
		// remove "page=" parameter to prevent last page error when increasing "showby"
		$link = preg_replace('/(&?)page=(\d+)/', '', $request->getReferer());
		$this->redirect($link);
	}
	
	
	public function executeShowin(sfWebRequest $request){
		if(!isset( categoryPageActions::$showIn[$this->getRequestParameter('val')] )) return sfView::NONE;
		
		$this->getUser()->setAttribute('showin', $this->getRequestParameter('val'));
		
		$this->redirectToReferer();
	}

	
	protected function processReminderForm($form){
		sfProjectConfiguration::getActive()->loadHelpers(array('I18N', 'Variable'));
		
		$form->bind($this->getRequestParameter($form->getName()));
		
		
		if($form->isValid()){
			if(($usr = Doctrine::getTable('PublicUser')->findOneByEmail($form->getValue('email')))){
				$message = $this->getMailer()
								->compose(	array( variable('reminder email','aneto1@gmail.com') => __('Password reminder bot') ),
												  	$usr->getEmail(),
													__('Password reminder'),
													__('Your password is %1%', array('%1%' => $usr['password']))
										);
	 
	    		return $this->getMailer()->send($message);
			}
		}
		
		return false;
	}
	
	
	protected function redirectToReferer(){
		if( $this->getRequest()->getReferer() )
			$this->redirect( $this->getRequest()->getReferer() );
		else{
			$this->redirect( $this->getComponent('linker', 'localizedHomepage') );
		}
	}


        public function executeExportGroups(){
            $this->groups = Doctrine::getTable('ProductGroup')->findAll();
            $this->setlayout('csv');
            $this->getResponse()->clearHttpHeaders();
            $this->getResponse()->setHttpHeader('Content-Type', 'application/vnd.ms-excel');
            $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename=export_group.csv');
      }

        public function executeExportProds(){
            $this->prods = Doctrine::getTable('Product')->findAll();
            $this->setlayout('csv');
            $this->getResponse()->clearHttpHeaders();
            $this->getResponse()->setHttpHeader('Content-Type', 'application/vnd.ms-excel');
            $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename=export.csv');
      }

        public function executeTest() {
          $this->setLayout(false);
//          $prods = Doctrine::getTable('Product')->findAll();
//          foreach ($prods as $prod) {
//            $prod->updateLuceneIndex();
//          }
//          $prods = Doctrine_Query::create()->select('*')->from('ShippingZone sz')->where('sz.id > 8')->execute();
//          foreach ($prods as $prod) {
//            $int = new ShippingZoneInterval();
//            $int->setMyZoneId($prod->getId());
//            $int->setStart('100');
//            $int->setEnd('1000');
//            $int->setPrice('3.20');
//            $int->save();
//
//            $int2 = new ShippingZoneInterval();
//            $int2->setMyZoneId($prod->getId());
//            $int2->setStart('1001');
//            $int2->setEnd('10000');
//            $int2->setPrice('5.00');
//            $int2->save();
//          }
//          $query = Doctrine_Query::create()
//                   ->select('sz.*, tt.*, si.*, ztt.*')
//                   ->from('ShippingZone sz')
//                   ->innerJoin('sz.ZoneTransportType ztt')
//                   ->innerJoin('ztt.TransportType tt')
//                   ->innerJoin('sz.Intervals si')
//                   ->where('tt.id = ?', 2)
//                   ->execute();
//          $max = 0;
//          $min = 0;
//          foreach ($query as $zone) {
//            foreach($zone['Intervals'] as $interval) {
//              if ($interval['start'] < $min) {
//                $min = $interval['start'];
//              }
//              if ($interval['end'] > $max) {
//                $max = $interval['end'];
//              }
//            }
//          }
//          $type = $query[0]['ZoneTransportType'][0]['TransportType'];
//          $type->setMinWeight($min);
//          $type->setMaxWeight($max);
//          $type->save();
        }
}